﻿using General.Services.Template;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
using General.Core.Config;
using Microsoft.Extensions.Caching.Memory;

namespace General.Mvc.Filters
{
    public class PageTemplateFilter : ActionFilterAttribute
    {
        private const string ResponseTimeKey = "ResponseTimeKey";
        private readonly ILogger logger;

        private readonly ITemplateService templateService;
        private readonly IMemoryCache memoryCache;

        public PageTemplateFilter(ILogger<PageTemplateFilter> logger,
            ITemplateService templateService,
            IMemoryCache memoryCache)
        {
            this.logger = logger;
            this.templateService = templateService;
            this.memoryCache = memoryCache;
        }

        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            // Start the timer   
            context.HttpContext.Items[ResponseTimeKey] = Stopwatch.StartNew();
            //获取模板html内容加载到内存
            await templateService.GetTemplateHtmlPages();
            var resultContext = await next();
            //是否关闭网站
            if (!WebSiteConfig.WebSite_IsOpen)
            {
                ContentResult content = new ContentResult() { StatusCode = 200, Content = memoryCache.Get("WebSite_CloseNoice").ToString(), ContentType = "text/html;charset=utf-8" };
                resultContext.HttpContext.Response.ContentType = "text/html;charset=utf-8";
                resultContext.Result = content;
                return;
            }
        }

        public override async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            if (context.Result.GetType().Name != "ContentResult")
            {
                await next();
                return;
            }
            var contentResult = (ContentResult)context.Result;
            Stopwatch stopwatch = (Stopwatch)context.HttpContext.Items[ResponseTimeKey];
            // Calculate the time elapsed   
            var timeElapsed = stopwatch.Elapsed;

            var time = Convert.ToDecimal(timeElapsed.TotalMilliseconds / 1000);
            ContentResult content = new ContentResult() { StatusCode = 200, Content = contentResult.Content.Replace("@Execution_Time", time.ToString()) };
            context.Result = content;
            var resultContext = await next();
        }
    }
}
